
//
//  RequestManager.m
//  魔兽大数据
//
//  Created by 王右 on 2017/10/14.
//  Copyright © 2017年 王右. All rights reserved.
//

#import "RequestManager.h"
#import "RequestManager+Extand.h"
#import "CCJSONParse.h"
#import "CCCache.h"


typedef enum : NSUInteger {
    kErrorCodeTokenFail = 1,    //认证失败
    kErrorCodeFail,             //失败
    kErrorCodeAccess,           //权限
} kErrorCode;


static NSString *const kHostDomain = @"http://wowdata.top:8080/api/";
static NSString *const kBnadeHostDomain = @"https://api.bnade.com/";
static NSInteger const kTimeoutInterval =  15.0;
static NSString *const kErrorMessage= @"服务器出错,请稍后再试";
static NSString *const kErrorSpell = @"module错误,请检查拼写";

@implementation RequestManager

//http://wowdata.top:8080/api/playerstatistics/findAll  人口普查 接口OK
//http://wowdata.top:8080/api/goldsell/findAll   金价查询 OK


//header
+ (AFHTTPSessionManager*)afmanager {
    static AFHTTPSessionManager* manager = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json",@"text/plain",@"text/json",@"application/javascript",@"application/x-javascript" ,@"text/javascript",@"text/x-javascript",@"text/x-json",nil];
        manager.requestSerializer.timeoutInterval = kTimeoutInterval;
    });
    return manager;
}

+ (void)requestGetBnadeWithModule:(NSString *)module
                    param:(NSDictionary *)param
                    model:(NSString *)model
                  success:(void (^)(id obj))success
                  failure:(void (^)(NSString *error))failure{
    
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定~");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kBnadeHostDomain,module];
    id result = [[CCCache defaultManager] objectForKey:url];
    if (result != nil) {
        //如果有网络请求缓存
        success(result);
        return;
    }
    [[self afmanager] GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        id data = resultObject;
        id result;
        Class objClass = NSClassFromString(model);
        if ([data isKindOfClass:[NSArray class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithArray:data ingoreChange:NO];
            }
            
        }
        if ([data isKindOfClass:[NSDictionary class]]) {
            if ([model isEqualToString:@""]) {
                result = [objClass objectWithDictionary:data ingoreChange:NO];
            }
        }
        success(result);
        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定~");
    }];
}

+ (void)requestPostBnadeWithModule:(NSString *)module
                        param:(NSDictionary *)param
                        model:(NSString *)model
                      success:(void (^)(id obj))success
                      failure:(void (^)(NSString *error))failure{
    
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定~");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kBnadeHostDomain,module];
    id result = [[CCCache defaultManager] objectForKey:url];
    if (result != nil) {
        //如果有网络请求缓存
        success(result);
        return;
    }
    [[self afmanager] POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(resultObject);
        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定~");
    }];
}

+ (void)requestGetBigDataWithModule:(NSString *)module
                            param:(NSDictionary *)param
                            model:(NSString *)model
                          success:(void (^)(id obj))success
                          failure:(void (^)(NSString *error))failure{
    
    if (![RequestManager isNetWorkReachable]){
        failure(@"服务器出错或网络不稳定~");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomain,module];
    id result = [[CCCache defaultManager] objectForKey:url];
    if (result != nil) {
        //如果有网络请求缓存
        success(result);
        return;
    }
    [[self afmanager] GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        id data = resultObject[@"data"];
        id result;
        Class objClass = NSClassFromString(model);
        if ([data isKindOfClass:[NSArray class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithArray:data ingoreChange:NO];
            }
        }
        if ([data isKindOfClass:[NSDictionary class]]) {
            if (![model isEqualToString:@""]) {
                result = [objClass objectWithDictionary:data ingoreChange:NO];
            }
        }
        success(result);
        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定~");
    }];
}

+ (void)requestPostBigDataWithModule:(NSString *)module
                             param:(NSDictionary *)param
                             model:(NSString *)model
                           success:(void (^)(id obj))success
                           failure:(void (^)(NSString *error))failure{
    
    if (![RequestManager isNetWorkReachable]) {
        failure(@"服务器出错或网络不稳定~");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kHostDomain,module];
    id result = [[CCCache defaultManager] objectForKey:url];
    if (result != nil) {
        //如果有网络请求缓存
        success(result);
        return;
    }
    [[self afmanager] POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(resultObject);
        [[CCCache defaultManager] setObject:result forKey:url duration:3 * 60];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定~");
    }];
}



+ (void)requestTestSuccess:(void (^)(id))success failure:(void (^)(NSString *))failure{
    [[self afmanager] GET:@"https://api.bnade.com/realms" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id resultObject;
        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"服务器出错或网络不稳定~");
    }];
}


+ (void)testPost{
//    https://y.bnytzyy.com:8443/bnytwebservice/EcaseHistory/saveDoctorNote.do?clientId=dbb645cfbb1f4acc9db75360db27194c&token=d6318d04aaccab3dc150e90fda16952f66ec4b28c498f3e943101101fe9c2f52c49ef2021ec49342ebe6d97ddb7925e2&eId=6e178c9db93644e7ade61740d699b013&orderId=9a0973b62b684758a0e8b345979cef28&mainComplaint=测试&animalHeat=高烧&pubse=过速&bloodPressure=高血压&heartRate=过速&breathe=困难&psychosis=亢奋&takeMedicine=我们的
    
//    NSMutableArray *titleArr = @[@"我的服务器",@"人口普查",@"金币价格",@"时光徽章",@"设置",@"关于我们"].mutableCopy;
//
//    NSDictionary *dic = @{@"clientId":@"dbb645cfbb1f4acc9db75360db27194c",@"token":@"0e1d92212e9669bc1135407d6c6511243d9c60d10a1cdf5b627e0c17a89cbb16c8f49d7efbe4d7c1c73fe174ecad696f",@"eId":@"6e178c9db93644e7ade61740d699b013",@"orderId":@"9a0973b62b684758a0e8b345979cef28",@"mainComplaint":@"测试",@"animalHeat":@"高烧",@"pubse":@"过速",@"bloodPressure":@"高血压",@"heartRate":@"过速",@"breathe":@"困难",@"psychosis":@"亢奋",@"takeMedicine":@"我们的"};
//    [[self afmanager] POST:@"https://y.bnytzyy.com:8443/bnytwebservice/EcaseHistory/saveDoctorNote.do" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [titleArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            UIImage *image = [UIImage imageNamed:obj];
//            NSData *data = UIImageJPEGRepresentation(image, 0.01);
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            formatter.dateFormat = @"yyyyMMddHHmmss";
//            NSString *str = [NSString stringWithFormat:@"%@_%@",[formatter stringFromDate:[NSDate date]],@(idx)];
//            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
//            //服务器上传文件的字段和类型
//            [formData appendPartWithFileData:data name:fileName fileName:fileName mimeType:@"image/jpeg"];
//        }];
//
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        id resultObject;
//        resultObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@",resultObject);
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
//    }];
//
    
    
    
}










@end
